import { defineStore } from 'pinia';
import type { User } from '@/types/api';
import { useLoginModal } from '@/composables/useLoginModal'; // 假设这个文件路径正确

// 用户状态接口
export interface UserState {
  // 用户信息
  user: User | null;
  // 认证token
  token: string | null;
  // 是否已登录
  isLoggedIn: boolean;
  // 登录时间
  loginTime: number | null;
  // 展示新手指引
  userGuideStep: any; // 99新人引导Modal 1-4新人指引step Modal
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user: null,
    token: null,
    isLoggedIn: false,
    loginTime: null,
    userGuideStep: null,
  }),

  getters: {
    // 获取用户ID
    userId: (state) => state.user?.id || null,

    // 获取用户邮箱
    userEmail: (state) => state.user?.email || '',

    // 获取用户名
    username: (state) => state.user?.name || '',

    // 获取用户头像
    userAvatar: (state) => state.user?.avatar || '',

    // 检查是否已登录
    isAuthenticated: (state) => {
      return state.isLoggedIn && state.token !== null && state.user !== null;
    },
    newUserGuideStep: (state) => state.userGuideStep,
  },

  actions: {
    /**
     * 登录成功处理
     * @param data 登录响应数据
     */
    loginSuccess(data: any) {
      console.log(data, 'data====');

      const { token } = data;

      // 更新状态（插件会自动持久化）
      this.token = token;
      this.user = data.user;
      this.isLoggedIn = true;
      this.loginTime = Date.now();
      console.log('data.user?.is_new === 1', data.user?.is_new === 1);
      if (data.user?.is_new === 1) {
        console.log('00000new');
        this.userGuideStep = 99;
      }
    },

    setNewUserGuideStep(step: number | null) {
      this.userGuideStep = step;
    },

    /**
     * 登出
     */
    async logout() {
      this.user = null;
      this.token = null;
      this.isLoggedIn = false;
      this.loginTime = null;
      console.log('用户已登出');
    },

    /**
     * 更新用户信息
     * @param userInfo 要更新的用户信息
     */
    updateUserInfo(userInfo: Partial<User>) {
      if (this.user) {
        this.user = { ...this.user, ...userInfo };
        console.log('用户信息已更新:', this.user);
      }
    },

    /**
     * 检查用户是否已登录，如果未登录则显示登录弹窗
     * @returns boolean 是否已登录
     */
    checkAndShowLogin(): boolean {
      if (!this.isAuthenticated) {
        const { showModal } = useLoginModal();
        showModal();
        return false;
      }
      return true;
    },
  },

  // 配置持久化
  persist: true,
});
